package com.itheima.task.task;

import com.itheima.task.service.DelayQueueService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * 延迟队列定时任务
 */
@Component
@Slf4j
public class DelayQueueTask {

    @Autowired
    private DelayQueueService delayQueueService;

    @Value("${delay-queue.scan-interval:5000}")
    private long scanInterval;

    @Value("${delay-queue.consume-interval:2000}")
    private long consumeInterval;
    
    @PostConstruct
    public void init() {
        log.info("延迟队列定时任务初始化完成 - 扫描间隔: {}ms, 消费间隔: {}ms", scanInterval, consumeInterval);
    }

    /**
     * 扫描延迟队列，转移到期任务到就绪队列
     */
    @Scheduled(fixedDelayString = "${delay-queue.scan-interval:5000}")
    public void scanDelayQueue() {
        try {
            delayQueueService.scanExpiredTasks();
        } catch (Exception e) {
            log.error("扫描延迟队列异常", e);
        }
    }

    /**
     * 消费就绪队列中的任务
     */
    @Scheduled(fixedDelayString = "${delay-queue.consume-interval:2000}")
    public void consumeReadyQueue() {
        try {
            delayQueueService.consumeReadyTasks();
        } catch (Exception e) {
            log.error("消费就绪队列异常", e);
        }
    }
}

